package com.huluobo.a2107mvpimdemo.base;

import java.lang.ref.WeakReference;

import io.reactivex.disposables.CompositeDisposable;

/**
 * P层的基准类
 * 内存引用4种形式 强 弱 软 虚
 * 1.强引用,User user = new User(), 程序宁可报错,也不会销毁当前的引用
 * 2.弱引用WeakReference<User> user = new WeakReference() 只要发生GC(垃圾回收机制) ,就会回收掉
 * 3.软引用 SoftReference<User> user = new SoftReference().只要内存不足的时候才会被回收
 * 4.虚引用 一般不用,有时候可能都拿不到对象
 * Created by LC on 2023/9/20.
 */
public class BasePresenter<V> {
    private WeakReference<V> weakReference;

    protected CompositeDisposable compositeDisposable = new CompositeDisposable();

    //绑定视图
    public void attachView(V view) {
        if (weakReference == null) {
            weakReference = new WeakReference<>(view);
        }
    }

    //解绑视图
    public void disAttach() {
        if (weakReference != null) {
            weakReference.clear();
            weakReference = null;
        }

        if (compositeDisposable != null) {
            compositeDisposable.clear();
            compositeDisposable = null;
        }
    }

    //判断是否被视图绑定
    public Boolean isAttach() {
        return weakReference != null && weakReference.get() != null;
    }

    //获取当前视图
    public V getView() {
        if (weakReference != null && weakReference.get() != null) {
            return weakReference.get();
        }
        return null;
    }
}
